package com.shelpe.services.algorithm.autoDrive;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.shelpe.services.algorithm.client.LexiconClient.RecommendWordDto;
import com.shelpe.services.algorithm.client.SinbadClient;
import com.shelpe.services.algorithm.client.SinbadClient.HandlingKeyword;
import com.shelpe.services.algorithm.configuration.MobileQscoreProperties;
import com.shelpe.services.algorithm.entity.jpa.Adgroup;
import com.shelpe.services.algorithm.entity.jpa.AutoProductQueue;
import com.shelpe.services.algorithm.entity.jpa.Campaign;
import com.shelpe.services.algorithm.repository.jpa.CampaignRepository;

import lombok.extern.slf4j.Slf4j;

@Service
@Slf4j
public class HighBudgetMobileRecommendWordFilter extends MobileRecommendWordFilter {

	@Autowired
	private CampaignRepository campaignRepository;
	
	@Autowired
	private MobileQscoreProperties mobileQscoreProperties;
	
	@Override
	public boolean support(Adgroup adgroup, AutoProductQueue queue) {
		boolean isMobile = super.support(adgroup, queue);
		Campaign campaign = this.campaignRepository.findOne(adgroup.getCampaignID());
		
		boolean support = isMobile && campaign!=null && campaign.getBudget()>70;
		if(support){
			log.debug("high budget mobile recommend filter: {}", adgroup);
		}
		return support;
	}
	@Override
	public List<HandlingKeyword> filter(List<RecommendWordDto> recommends, AutoProductQueue queue, Adgroup adgroup) {
		SortRes res = this.sort(recommends);
		List<AutoWordDto> words = res.getWords();
		
		List<SinbadClient.HandlingKeyword> handlingWords = new ArrayList<SinbadClient.HandlingKeyword>();
		for (AutoWordDto word : words) {
			log.debug("check word: {}", word);
			SinbadClient.HandlingKeyword keyword = this.toKeyword(word, adgroup.getLimit()/5, adgroup.getLimit());
			if(word.getRecomend().getPertinence() >= 40 
					&& word.getRecomend().getClickRatio() >= 0.01 
					&& word.getRecomend().getClickCoverage() >= 0.01 
					&& (keyword.getMaxPrice() >= 5 || keyword.getMaxMobilePrice() >= 5)
					&& word.getRecomend().isCenteral()
					&& word.getRecomend().getWord().length() > 3
					&& word.getRecomend().getClickRatio() >= (res.getMax().getAverageCtr() / 2)){
				handlingWords.add(keyword);
			}else{
				log.debug("not add as keyword: {}", word);
			}
		}
		return handlingWords;
	}
	@Override
	protected MobileQscoreProperties getMobileQscoreProperties() {
		return this.mobileQscoreProperties;
	}
	
}
